package com.zlll.winner.controller.mall;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.model.mall.MallSeckillManage;
import com.zlll.winner.business.service.mall.IMallSeckillManageService;
import com.zlll.winner.common.BaseController;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/mallSeckill")
public class MallSeckillController extends BaseController {

    @Reference
    private IMallSeckillManageService iMallSeckillManageService;

    @PostMapping("getPage")
    public Object getPage(@RequestBody JSONObject data) {
        Long time = data.getLong("time");
        Integer pageNo = data.getInteger("pageNo") == null ? 1 : data.getInteger("pageNo");
        Integer pageSize = data.getInteger("pageSize") == null ? 20 : data.getInteger("pageSize");
        String goodsName = data.getString("goodsName");

        return iMallSeckillManageService.getMallSeckillByCondition(time, goodsName, pageSize, pageNo);
    }

    @PostMapping("add")
    public Object add(@RequestBody JSONObject data) throws Exception {


        Long startTime = data.getLong("startTime");
        Long endTime = data.getLong("endTime");
        List<Map<String, Object>> externals = (ArrayList) data.get("externals");
        if (iMallSeckillManageService.isrepeat(startTime, endTime).size() > 0) {
            throw new Exception("秒杀活动时间有重复，请重新选择时间！");
        }
        return iMallSeckillManageService.add(startTime, endTime, externals, getUserId());
    }

    @PostMapping("get/{id}")
    public Object getMallSeckillManageById(@PathVariable Long id) {
        return iMallSeckillManageService.getMallSeckillManageById(id);
    }

    @PostMapping("edit")
    public Object edit(@RequestBody JSONObject data) throws Exception {
        Long startTime = data.getLong("startTime");
        Long endTime = data.getLong("endTime");
        Long id = data.getLong("id");
        List<Map<String, Object>> externals = (ArrayList) data.get("externals");

        List<MallSeckillManage> list = iMallSeckillManageService.isrepeat(startTime, endTime);
        if (list.size() > 1) {
            throw new Exception("秒杀活动时间有重复，请重新选择时间！");
        } else if (list.size() == 1) {
            if(!id.equals(list.get(0).getId())){
                throw new Exception("秒杀活动时间有重复，请重新选择时间！");
            }
        }
        return iMallSeckillManageService.edit(id,startTime, endTime, externals, getUserId());
    }


    @PostMapping("delete/{seckiilNo}")
    public Object getMallSeckillManageById(@PathVariable String  seckiilNo) {
        return iMallSeckillManageService.deleteMallSeckillManage(seckiilNo,getUserId());
    }
}
